package com.jijs.mywsdl.client;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;

public class ClientTest {
	
	public static void excute1() throws MalformedURLException {
//		MyCalcImplService mis = new MyCalcImplService();
//		IMyCalc ms = mis.getMyCalcImplPort();
//		System.out.println(ms.divide(29, 3));
//		System.out.println(ms.add(3, 4));
		
		URL url = new URL("http://localhost:8989/ms");
		String ns = "http://www.jijs.com/mywsdl/";
		QName qname = new QName(ns, "MyCalcImplService");
		Service service = Service.create(url, qname);
		
		IMyCalc calc =  service.getPort(IMyCalc.class);
		System.out.println(calc.add(3, 5));
		System.out.println(calc.divide(30, 3));
	}
	
	public static void excute2() throws SOAPException, IOException{
		URL url = new URL("http://localhost:8989/ms?wsdl");
		String ns = "http://www.jijs.com/mywsdl/";
		QName qname = new QName(ns, "MyCalcImplService");
		
		Service service = Service.create(url, qname);
		//<wsdl:port binding="tns:myCalcSOAP" name="MyCalcImplPort">
		QName portName = new QName(ns, "MyCalcImplPort");
		Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
		
		SOAPMessage msg = MessageFactory.newInstance().createMessage();
		SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
		SOAPBody body = env.getBody();
		SOAPHeader header = env.getHeader();
		if(header == null){
			env.addHeader();
		}
		//一定要加ns前缀
		QName licenseName = new QName(ns, "licenseInfo", "ns");
		header.addHeaderElement(licenseName).setValue("licenseinfo");
		
		QName addName = new QName(ns, "add", "ns");
		//添加body信息
		SOAPBodyElement bodyEle = body.addBodyElement(addName);
		bodyEle.addChildElement("a").setValue("12");
		bodyEle.addChildElement("b").setValue("33");
		
		msg.writeTo(System.out);
		System.out.println("\n invoking...");
		
		SOAPMessage rep = dispatch.invoke(msg);
		rep.writeTo(System.out);
	}

	public static void main(String[] args) throws SOAPException, IOException {
//		excute1();
		excute2();
	}
}
